﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DbDoc.BusinessObjects;
using DbDoc.BusinessManager;
using System.Windows;

namespace DbDoc.PowerDoc.ViewModel
{
    class LoginViewModel : ViewModelBase
    {
        #region Member Variables
        private string _Username;
        private string _Password;
        private DelegateCommand _LoginCommand;
        private bool _IsUserAuthenticated;
        private AppUser _LoggedUser;
        private string _Message;
        private Window _CurrentView;
        #endregion

        #region Properties

        public bool IsUserAuthenticated
        {
            get { return _IsUserAuthenticated; }

        }
        public DelegateCommand LoginCommand
        {
            get
            {
                if (_LoginCommand == null)
                    _LoginCommand = new DelegateCommand(param => OnLoginCommandExecuted(), param => CanLoginExecute());
                return _LoginCommand;
            }
            set { _LoginCommand = value; }
        }


        public string Message
        {
            get { return _Message; }
            set
            {
                _Message = value;
                OnPropertyChanged("Message");
            }
        }


        public string Username
        {
            get { return _Username; }
            set
            {
                _Username = value;
                OnPropertyChanged("Username");
            }
        }
        public string Password
        {
            get { return _Password; }
            set
            {
                _Password = value;
                OnPropertyChanged("Password");
            }
        }

        public AppUser LoggedUser
        {
            get { return _LoggedUser; }
            set
            {
                _LoggedUser = value;
                OnPropertyChanged("LoggedUser");
            }
        }
        #endregion

        public LoginViewModel(Window currentWindow)
        {
            _CurrentView = currentWindow;
        }

        private object OnLoginCommandExecuted()
        {
            AppUser user = AppUserManager.Login(Username, Password);
            if (user == null)
            {
                Message = "Invalid username or password.";
                return null;
            }
            LoggedUser = user;
            IRequestClose closeView = (IRequestClose)_CurrentView;
            closeView.CloseMe();
            return user;
        }

        private bool CanLoginExecute()
        {
            return true;
            return (!string.IsNullOrWhiteSpace(Username) &&
                !string.IsNullOrWhiteSpace(Password));
        }

    }
}
